$(function(){
	//百度统计
	$("#settlementBtn").on("click", function(){
		_hmt.push(['_trackEvent', '去结算PC', 'click', '去结算PC']);
	})
	//返回顶部
	addGotop();
	//单选按钮
	$(".shop-main").on("click", "li:not(.dis) .shop-select .icon", function(){
		toggleSelect($(this));
		selectedSum();
	});
	//全选
	$(".shop-title .icon").on("click",function(){
		selectAll($(this));
		toggleSelect($(".settlement-selectall").children(".icon"));
		selectedSum();
	});
	//全选
	$(".settlement-selectall").on("click", function(){
		selectAll($(this).children(".icon"));
		toggleSelect($(".shop-title .icon"));
		selectedSum();
	});
	//删除
	$(".shop-list").on("click", ".shop-del", function(){
		var _this = this;
		$.confirm("确定要删除该商品？", function(){
			cartProccess(cartDelUrl, {
				cartIds: $(_this).closest("li").attr("data-cart-id"),
				selectedIds:getSelected()
			}, function(data){
				if(data.flag){
					$(_this).parentsUntil(".shop-list","li").remove();
					$(".shop-list li").size()<=1&&$(".shop-main").hide().siblings(".shop-none").show();
					setSettle(data);
					$(window).trigger("scroll");//修复删除商品时数量过少结算栏没有跟上去bug
				}else{
					$.alert(data.msg);
				}
			});
		});
	});
	//删除选中
	$(".settlement-del").on("click", function(){
		var _this = this;
		var selected = $(".shop-list li:not(.dis) .shop-select .icon-stock-selected").closest("li");
		if(selected.size()>0){
			$.confirm("确定要删除选中的商品吗？", function(){
				var selecteds = getSelected();
				cartProccess(cartDelUrl, {
					cartIds: selecteds,
					selectedIds:selecteds
				}, function(data){
					if(data.flag){
						var selectedArr = selecteds.split(",");
						$.each(selectedArr, function(i){
							$(".shop-list li[data-cart-id='"+selectedArr[i]+"']").remove();
						});
						$(".shop-list li").size()<=1&&$(".shop-main").hide().siblings(".shop-none").show();
						setSettle(data);
						$(window).trigger("scroll");//修复删除商品时数量过少结算栏没有跟上去bug
					}else{
						$.alert(data.msg);
					}
				});
			});
		}else{
			$.alert("请选择需要删除的商品");
		}
	});
	//商品数量编辑器
	$(document).on("click", ".amount-reduce", function(){
		var input = $(this).next("input");
		if(input.data("disabled")||$(this).is(".dis")){
			return false;
		}else{
			var m = input.val()||0;
			m--;
			input.data("amount", m).trigger("change");
		}		
	}).on("click", ".amount-add", function(){
		var input = $(this).prev("input");
		if(input.data("disabled")||$(this).is(".dis")){
			return false;
		}else{
			var m = input.val()||0;
			m++;
			input.data("amount", m).trigger("change");
		}
	}).on("change", ".amount-input", function(e,init){
		var _this = this;
		var max = parseInt($(this).attr("size"))||199;
		var min = 1;
		var state = true;
		var curVal = $(this).val();
		var m = $(this).data("amount")||curVal;//点加减号运算后的数量值，存储起来，等请求响应后显示
		var lastVal = $(this).data("lastVal")||curVal;
		if($.isEmpty(m)||m===false){
			m = $(this).val()
		}else{
			m = parseInt(m);
		}
		if(m<min||m>max||isNaN(m)){
			state = false;
			m = lastVal;
		}
		if(m<max||m>min){
			$(this).siblings().removeClass("dis");
		}
		if(m==max){
			$(this).next().addClass("dis");
		}
		if(m==min){
			$(this).prev().addClass("dis");
		}
		//sum(this,m);
		var curLi = $(this).closest("li");
		if(!init&&state){
			$(_this).data("disabled",true);
			cartProccess(changeNumUrl, {
				cartId: curLi.attr("data-cart-id"), 
				number: m,
				selectedIds: getSelected
			}, function(data){
				data.flag||$.alert(data.msg);
				$(_this).val(data.number)
				.data({"disabled":false,"amount":false,"lastVal":m})
				.closest("li").children(".shop-sum").text(data.sumPrice==0?(data.sumSd+"试豆"):("￥"+data.sumPrice));
				setSettle(data);
			});
		}else{
			lastVal>max&&(lastVal=max);
			$(_this).val(m).data({"disabled":false,"amount":false,"lastVal":lastVal})
		}
	});
	//初始化数量编辑器
	$(".shop-list .amount-input").trigger("change",true);//告诉change事件这是初始化，不要发请求
	//结算按钮浮动
	var settlementFix = $(".settlement-wrap");
	settlementFix.size()>0&&whileToObject(settlementFix, function(){
		$(".settlement").removeClass("fixbottom")
	}, function(){
		$(".settlement").addClass("fixbottom")
	});
	//去结算
	$("#settlementBtn").on("click", function(){
		var cart_ids = getSelected();
		if(cart_ids==""){
			$.alert("请选择商品");
			return false;
		}else{
			settleCart(cart_ids, function(){
				$("[name='cart_ids']").val(cart_ids);
				$("#_csrf").val($('meta[name="csrf-token"]').attr("content"));
				$("#cartForm").submit();
			});
		}
	});
})
//切换复选框状态-参数o:jq对象
function toggleSelect(o){
	o.is(".icon-stock-selected")?o.attr("class","icon icon-stock"):o.attr("class","icon icon-stock-selected");
}
//全选
function selectAll(o){
	var listSelect = $(".shop-list li:not(.dis) .shop-select .icon");
	o.is(".icon-stock-selected")?listSelect.attr("class","icon icon-stock"):listSelect.attr("class","icon icon-stock-selected");
	toggleSelect(o);
}
//购物车数据处理
function cartProccess(url, data, callback){
	$.doAjax({
		url: url,
		type: "post",
		data: data,
		success: $.isFunction(callback)&&callback
	});
}
//获取选中商品id集合
function getSelected(){
	return $(".shop-list ul li").has(".icon-stock-selected").map(function(){return $(this).attr("data-cart-id")}).get().join(",")
}
//选中商品结算
function selectedSum(){
	var cartIds = getSelected();
	if(cartIds == '') {
		resetCart();
		return false;
	}
	cartIds!=""&&cartProccess(selectUrl, {
		cart_ids: getSelected()
	}, function(data){
		data.flag||$.alert(data.msg);
		setSettle(data);
	});
}
//设置结算总结额
function setSettle(data){
	var selectedAmount = 0;
	$(".shop-list li .icon-stock-selected").each(function(){
		selectedAmount += $(this).parent().siblings(".shop-amount").find(".amount-input").val()*1;
	});
	$(".settlement-selected i").text(selectedAmount);
	$(".settlement-sum-rmb").text("￥"+(data.order_amount||'0.00'));
	$(".settlement-sum-sd").text(data.try_coin||'0');
	$("#fullcut").text(data.fullcut);
	$("#reduceAmount").text("￥"+(data.reduce_amount||'0.00'));
}
//结算购物车
function settleCart(cart_ids, callback){
	$.doAjax({
		url: settleCartUrl,
		type: "post",
		data: {cart_ids: cart_ids},
		success: function(data){
			if(data.flag){
				$.isFunction(callback)&&callback(data);
			}else{
				var str = '';
				for(var m in data.msg){
					for(var i=0;i<data.msg[m].length;i++){
						str+=data.msg[m][i]+'</br>';
					}
				}
				$.alert('<p style="width:400px;margin:-20px 0;">'+str+'</p>');
			}
		}
	});
}
//购物车重置
function resetCart(){
	$("#fullcut").text(fullcut);
	$(".settlement-selected i").text(0);
	$(".settlement-sum-rmb").text("￥0.00");
	$(".settlement-sum-sd").text(0);
	$("#reduceAmount").text("￥0.00");
}












